package com.kun.lagou.controller;

import com.kun.lagou.service.impl.UrlMapService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Map;

/**
 * @author Administrator
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class ShrotMapController {
    private static final String DOMAIN = "127.0.0.1:8080";
    private final UrlMapService urlMapService;

    @PostMapping("/shorten")
    public Map shorten(@RequestParam("longUrl") String longUrl) {

        return Map.of("shortUrl", DOMAIN + "/view/" + urlMapService.encode(longUrl));
    }

    @GetMapping("/view/{shortKey}")
    public RedirectView redirect(@PathVariable("shortKey") String shortKey) {
        return urlMapService.decode(shortKey).map(RedirectView::new).orElse(new RedirectView("/sorry"));
    }

    @GetMapping("/sorry")
    public String sorry() {
        return "抱歉，没有找到页面！";
    }
}
